// options menu
// methods: init context menus, onclick events
// export: optionsAvail, optionsMenuOnInstalled, optionsMenuOnClicked

// list of available options and attributes
// key: for simple identification; title: for display
export let optionsAvail = {
    tabs: {
        selected: { title: "Selected", type: "radio", default: true },
        currentWindow: { title: "Current Window", type: "radio", default: false },
        allWindows: { title: "All Windows", type: "radio", default: false }
    },
    format: {
        markdown: { title: "Markdown", type: "radio", default: true },
        siyuan: { title: "SiYuan H3", type: "radio", default: false }
    },
    modify: {
        title: { title: "Trim Title", type: "checkbox", default: true },
        url: { title: "Trim Url (?#)", type: "checkbox", default: true },
    }
};

/**
 * Initialize storage options from optionsAvail
 * @returns {Object} options for storage
 */
function initOptionsStorage() {
    let options = {};
    // groups of radio-type: save the selected one
    for (let group of ["tabs", "format"]) {
        for (let item in optionsAvail[group]) {
            if (optionsAvail[group][item]["default"]) {
                options[group] = item;
            }
        };
    };
    options["format2"] = options["format"] === "markdown" ? "siyuan" : "markdown";
    // groups of checkbox-type: specify state for each one
    for (let item in optionsAvail["modify"]) {
        options[`modify${item}`] = optionsAvail["modify"][item]["default"];
    };
    return options
};

/**
 * Set icon title as a list of current stored options
 * used as callback function of chrome.storage.local.set()
 */
function setActionTitle() {
    chrome.storage.local.get(
        ["tabs", "format", "modifytitle", "modifyurl"],
        (options) => {
            let titleArr = ["Click Icon to Copy", "Options:"];
            // groups of radio-type: display selected one
            for (let group of ["tabs", "format", "format2"]) {
                let item = options[group];
                titleArr.push(optionsAvail[group][item]["title"]);
            };
            // groups of checkbox-type: display selected one
            for (let item of ["title", "url"]) {
                if (options[`modify${item}`]) {
                    titleArr.push(optionsAvail["modify"][item]["title"]);
                }
            }
            // join array, set title
            let titleObj = { "title": titleArr.join("\n") };
            chrome.action.setTitle(titleObj);
        }
    );
};

/**
 * Encode group,item to contextMenus id
 */
function encodeMenuId(group, item) {
    return `tabcopymod-${group}-${item}`
};

/**
 * Decode contextMenus id to group,item
 */
function decodeMenuId(menuId) {
    const idSplit = menuId.split("-");
    let group = idSplit[1];
    let item = idSplit[2];
    return [group, item]
};

/**
 * Uppercase the first letter of a string
 */
function upper1st(string) {
    return string.replace(/^\w/, c => c.toUpperCase())
};


/**
 * Initialize the storage and the options menu
 */
export function optionsMenuOnInstalled() {
    chrome.runtime.onInstalled.addListener(async () => {
        // setup storage
        chrome.storage.local.set(
            initOptionsStorage(),
            setActionTitle
        );

        // setup context menu
        // params for context menu
        const contextMenusType = ["action"];

        // group to display in menu's top level
        for (let group of ["format"]) {
            for (let item in optionsAvail[group]) {
                let values = optionsAvail[group][item];
                chrome.contextMenus.create({
                    id: encodeMenuId(group, item),
                    title: `${upper1st(group)}: ${values.title}`,
                    type: values.type,
                    checked: values.default,
                    contexts: contextMenusType
                });
            };
        };

        // a separator
        chrome.contextMenus.create({
            id: encodeMenuId("sep", "options"),
            type: "separator",
            contexts: contextMenusType
        });

        // groups to display in submenus
        for (let group of ["tabs", "modify"]) {
            // entry of the submenu
            chrome.contextMenus.create({
                id: encodeMenuId(group, "parent"),
                title: `Options: ${upper1st(group)}`,
                contexts: contextMenusType
            });
            // items in the submenu
            for (let item in optionsAvail[group]) {
                let values = optionsAvail[group][item];
                chrome.contextMenus.create({
                    id: encodeMenuId(group, item),
                    parentId: encodeMenuId(group, "parent"),
                    title: values.title,
                    type: values.type,
                    checked: values.default,
                    contexts: contextMenusType
                });
            };
        };
    });
};

/**
 * Update storage on clicking context menus
 */
export function optionsMenuOnClicked() {
    chrome.contextMenus.onClicked.addListener((info, tab) => {
        // tabcopymod-group-item -> group,item
        let [group, item] = decodeMenuId(info.menuItemId);

        // update storage for each case
        switch (group) {
            case "tabs":
                chrome.storage.local.set({ "tabs": item }, setActionTitle);
                break;
            case "format":
                let item2 = item === "markdown" ? "siyuan" : "markdown";
                chrome.storage.local.set({ "format": item, "format2": item2 }, setActionTitle);
                break;
            case "modify":
                switch (item) {
                    case "title":
                        chrome.storage.local.set({ "modifytitle": info.checked }, setActionTitle);
                        break;
                    case "url":
                        chrome.storage.local.set({ "modifyurl": info.checked }, setActionTitle);
                        break;
                };
        };
    });
}
